package sm.upgrade.api.impl;

import java.util.List;

import sm.util.SMMap;

public class InboxDataUpgradeInterceptor extends DefaultDataUpgradeInterceptor {
	private boolean checkUnique(double inboxId) {
		boolean isUnique = true;

		// check in the new datas
		for (SMMap newData : newDatas) {
			double newInboxId = (Double) newData.get("inbox_id");
			if (inboxId == newInboxId) {
				isUnique = false;
				break;
			}
		}

		if (isUnique) {
			// check in the old datas
			List<Object> inboxes = template.find(
					"from inbox where inbox_id = ?", inboxId);
			if (inboxes != null && inboxes.size() > 0) {
				isUnique = false;
			}
		}
		return isUnique;
	}

	@Override
	public void beforeSave(String entityName, SMMap data) {
		// do nothing

		if ("inbox".equals(entityName)) {
			double inboxId = (Double) data.get("inbox_id");
			while (!checkUnique(inboxId)) {
				inboxId++;
			}
			data.put("inbox_id", inboxId);
		}
	}
}
